package encryption;

import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

/**This class is used to generate the Private and Public key file.
 * The Public.key file and Private.key file will be generated in the
 * current directory.
 * @author Debadatta Mishra(PIKU)
 *
 */
public class KeyCreator{

	private PublicKey publicKey = null;
	private PrivateKey privateKey = null;

	public KeyCreator(int sz) throws NoSuchAlgorithmException{
		//create the key generator
		KeyPairGenerator k = KeyPairGenerator.getInstance("RSA");
		k.initialize(sz);//set the key size
		KeyPair keyPair = k.generateKeyPair();//generate the keys

		publicKey = keyPair.getPublic();
		privateKey = keyPair.getPrivate();
	}

	/**
	 * @return the {@link PublicKey}
	 */
	public PublicKey getPublicKey() {
		return publicKey;
	}

	/**
	 * @return the {@link PrivateKey}
	 */
	public PrivateKey getPrivateKey() {
		return privateKey;
	}
	/**
	 * @param filename of type String indicating
	 * the name of Public or Private key
	 * @param contents of the key
	 */
	public void writeKey(String filename, byte[] contents){
		try{
			FileOutputStream fos = new FileOutputStream(filename);
			fos.write(contents);
			fos.flush();
			fos.close();
		}catch (IOException e){
			e.printStackTrace();
		}
	}

}